//
//  ZYHRequest.m
//  SchoolClient
//
//  Created by mac on 15/10/29.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "ZYHRequest.h"
#import "Reachability.h"
#import "MD5Encryptor.h"
#import "DesEncryptor.h"

@implementation ZYHRequest

//这个函数是判断网络是否可用的函数（wifi或者蜂窝数据可用，都返回YES）
+ (BOOL)NetWorkIsOK{
    if(
       ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus]
        != NotReachable)
       &&
       ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus]
        != NotReachable)
       ){
        return YES;
    }else{
        return NO;
    }
}

#pragma mark 加密与拼接请求参数
//加密参数
-(NSString *)encryptSortedArray:(NSMutableArray *)parameters{
    
    NSString *str = @"{";
    for (NSString *parameter in parameters) {
        NSLog(@"parameter:%@",parameter);
        str = [str stringByAppendingFormat:@"%@%@",parameter,@","];
    }
    //把最后面的","号换成"}"
    NSRange range = {[str length]-1,1};   //location = [str length]-1 , length = 1;
    NSString *plainText = [str stringByReplacingCharactersInRange:range withString:@"}"];
    NSString *cipherText_MD5 = [MD5Encryptor encryptUseMD5:plainText];
    NSString *key = @"FvcxFtqp";
    NSString *cipherText_DES = [DesEncryptor encryptUseDES:cipherText_MD5 key:key];
    NSLog(@"加密原文:%@",plainText);
    NSLog(@"MD5密文:%@",cipherText_MD5);
    
    return cipherText_DES;
}

//拼接http请求参数
-(NSMutableString *)jointSortedArray:(NSMutableArray *)parameters{
    
    NSString *str1 = @"&";
    for (NSString *parameter in parameters) {
        str1 = [str1 stringByAppendingFormat:@"%@%@",parameter,@"&"];
    }
    NSMutableString *mstr = [NSMutableString stringWithString:str1];
    //把最后面的"&"号去除
    NSRange range1 = {[str1 length]-1,1};   //location = [str length]-1 , length = 1;
    [mstr deleteCharactersInRange:range1];
    NSLog(@"mstr:%@",mstr);
    
    return mstr;
}

#pragma mark 同步GET请求(加密)
-(NSData *)getSyncEncryptRequest:(NSString *)urlStr
                      parameters:(NSMutableDictionary *)parameters{
    
    //1.利用字符串自带的compare:方法进行排序
    NSArray *sortedKeys = [parameters.allKeys sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *sortedArray = [NSMutableArray array];
    for (NSString *key in sortedKeys) {
        NSString *value = parameters[key];
        NSString *sortedParam = [NSString stringWithFormat:@"%@=%@",key,value];
        [sortedArray addObject:sortedParam];
    }
    
    //2.加密参数
    NSString *cipherText_DES = [self encryptSortedArray:sortedArray];
    
    //3.拼接http请求参数
    NSMutableString *mstr = [self jointSortedArray:sortedArray];
    
    //4.拼接http请求地址
    NSString *httpURL = [NSString stringWithFormat:@"%@%@sign=%@%@",BASE_URL,urlStr,cipherText_DES,mstr];
    
    NSLog(@"DES密文:%@",cipherText_DES);
    NSLog(@"网络请求:%@",httpURL);
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:httpURL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error) {
        NSLog(@"同步get请求出错: %@",error);
    }
    
    return data;
}

#pragma mark 异步GET请求(加密)
-(void)getAsyncEncryptRequest:(NSString *)urlStr
                   parameters:(NSMutableDictionary *)parameters
                      success:(void(^)(id responseData))success
                      failure:(void(^)(NSError *error))failure{
    
    _success = success;
    _failure = failure;
    
  
    //1.利用字符串自带的compare:方法进行排序
    NSArray *sortedKeys = [parameters.allKeys sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *sortedArray = [NSMutableArray array];
    for (NSString *key in sortedKeys) {
        NSString *value = parameters[key];
        NSString *sortedParam = [NSString stringWithFormat:@"%@=%@",key,value];
        [sortedArray addObject:sortedParam];
    }
    
    //2.加密参数
    NSString *cipherText_DES = [self encryptSortedArray:sortedArray];
    
    //3.拼接http请求参数
    NSMutableString *mstr = [self jointSortedArray:sortedArray];
    
    //4.拼接http请求地址
    NSString *httpURL = [NSString stringWithFormat:@"%@%@sign=%@%@",BASE_URL,urlStr,cipherText_DES,mstr];
    
    NSLog(@"DES密文:%@",cipherText_DES);
    NSLog(@"网络请求:%@",httpURL);
    
    //5.发送请求获取产品信息
    _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:httpURL]
                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                   timeoutInterval:30];
    _connection = [[NSURLConnection alloc]initWithRequest:_request delegate:self];
    
}

#pragma mark 异步POST请求(加密)
-(void)postAsyncEncryptRequest:(NSString *)urlStr
                    parameters:(NSMutableDictionary *)parameters
                       success:(void (^)(id responseData))success
                       failure:(void (^)(NSError *error))failure{
    
    _success = success;
    _failure = failure;
    
    NSString *URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,urlStr];
    _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                   timeoutInterval:30];
    
    _request.HTTPMethod = @"POST";
    
    //1.利用字符串自带的compare:方法进行排序
    NSArray *sortedKeys = [parameters.allKeys sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *sortedArray = [NSMutableArray array];
    for (NSString *key in sortedKeys) {
        NSString *value = parameters[key];
        NSString *sortedParam = [NSString stringWithFormat:@"%@=%@",key,value];
        [sortedArray addObject:sortedParam];
    }
    
    //2.加密参数
    NSString *cipherText_DES = [self encryptSortedArray:sortedArray];
    
    //3.拼接http请求参数
    NSMutableString *mstr = [self jointSortedArray:sortedArray];
    
    //4.拼接http请求体
    NSString *httpBody = [NSString stringWithFormat:@"sign=%@%@",cipherText_DES,mstr];
    
    NSLog(@"DES密文:%@",cipherText_DES);
    NSLog(@"网络请求:%@",httpBody);
    
    //把拼接后的字符串转换为data，设置请求体
    _request.HTTPBody = [httpBody dataUsingEncoding:NSUTF8StringEncoding];
    
    //5.连接服务器
    _connection = [[NSURLConnection alloc]initWithRequest:_request delegate:self];
    
}

#pragma mark 异步POST请求
-(void)postAsyncRequest:(NSString *)urlStr
             parameters:(NSMutableDictionary *)parameters
                success:(void (^)(id responseData))success
                failure:(void (^)(NSError *error))failure{
    
    _success = success;
    _failure = failure;
    
    NSString *URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,urlStr];
    _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                   timeoutInterval:30];
    
    _request.HTTPMethod = @"POST";
    
    //1.把字典按key=value的方式排例
    NSMutableArray *mArray = [NSMutableArray array];
    for (NSString *key in parameters.allKeys) {
        NSString *value = parameters[key];
        NSString *parameter = [NSString stringWithFormat:@"%@=%@",key,value];
        [mArray addObject:parameter];
    }
    
    //2.拼接http请求体
    NSMutableString *httpBody = [self jointSortedArray:mArray];
    //把前面的"&"号去除
    NSRange range = {0,1};
    [httpBody deleteCharactersInRange:range];
    NSLog(@"网络请求body:%@",httpBody);
    
    //把拼接后的字符串转换为data，设置请求体
    _request.HTTPBody = [httpBody dataUsingEncoding:NSUTF8StringEncoding];
    
    //5.连接服务器
    _connection = [[NSURLConnection alloc]initWithRequest:_request delegate:self];
    
}

#pragma mark POST上传头像到服务器
-(void)postAsyncImageRequest:(NSString *)urlStr
                   headImage:(NSData *)imageData
                  parameters:(NSDictionary *)parameters
                     success:(void (^)(id responseData))success
                     failure:(void (^)(NSError *error))failure{
    
    _success = success;
    _failure = failure;
    
    //根据url初始化request
    NSString *URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,urlStr];
    _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]
                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                   timeoutInterval:30];
    
    _request.HTTPMethod = @"POST";
    
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传图片的data
    //NSData *data = UIImageJPEGRepresentation(image, 1);
    
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    //NSDictionary *params = @{@"mdUsers.id":@"22",@"file":@"data"};
    NSArray *keys= [parameters allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"file"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[parameters objectForKey:key]];
        }
    }
    
    //添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明file字段，文件名为currentImage.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"currentImage.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:imageData];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [_request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [_request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [_request setHTTPBody:myRequestData];

    //连接服务器
    NSLog(@"HTTPHead:%@",_request);
    NSLog(@"HTTPBody:%@",myRequestData);
    _connection = [[NSURLConnection alloc]initWithRequest:_request delegate:self];

}


#pragma mark - NSURLConnection Delegate Methods
//接收到服务器回应的时候调用此方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _responseData = [[NSMutableData alloc] init];
    //清空内容，准备接收新的数据
    //[_responseData setData:nil];
    [_responseData setLength:0];
    
}
//接收到服务器传输数据的时候调用，此方法根据数据大小执行若干次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse
{
    return nil;
}

//数据传完之后调用此方法
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection
{
    // NSString *receiveStr = [[NSString alloc]initWithData:_responseData encoding:NSUTF8StringEncoding];
    //NSLog(@"json结果为===%@",receiveStr);
    _success(_responseData);
    [_connection cancel];
    _connection = nil;
    
}
//网络请求过程中，出现任何错误（断网，连接超时等）会进入此方法
- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
{
    _failure(error);
    [_connection cancel];
    _connection = nil;
    
}



@end
